<?php

namespace App\Models\V6;

use App\Models\V1\BaseModel;
use DB;


class BookSentenceModel extends BaseModel
{

    protected $table = 'book_sentence';
    protected $fillable = ['book_name', 'content', 'bg_img', 'publish_date'];

    /**
     * 获得每天的一段话
     * @param $date string 日期
     * */
    public function get_day_sentence($date = '')
    {
        $db = DB::table('book_sentence')
            ->select('id', 'book_name', 'content', 'bg_img', 'like_users', 'publish_date')
            ->where('is_delete', 0);
        $date && $db->where('publish_date', $date);
        $sentenceInfo = $db->orderBy('id', 'desc')->first();
        if (!$sentenceInfo && $date) {
            $sentenceInfo = $this->get_day_sentence();
        }
        if ($sentenceInfo) {
            $time                    = strtotime($sentenceInfo->publish_date);
            $sentenceInfo->show_date = date('d/M', $time);
        }

        return $sentenceInfo;
    }


    /**
     * 获取句子列表
     * @param $all boolean 是否全部获取，主要用于后台
     *
     * */
    public function get_book_sentences($all = false)
    {
        $today = current_date();
        $db    = DB::table('book_sentence')
            ->select('id', 'book_name', 'content', 'bg_img', 'like_users', 'publish_date');
        if (!$all) {
            $db->where('publish_date', '<=', $today);
        }
        $sentences = $db->where('is_delete', 0)
            ->orderBy('id', 'desc')
            ->paginate(10);

        foreach ($sentences as $sentence) {
            $time                = strtotime($sentence->publish_date);
            $sentence->show_date = date('d/M', $time);
        }
        return $sentences;
    }


    /**
     * 获取句子的详细信息
     * @param $sentenceId integer 句子ID
     * @param $userId integer 用户ID
     * */
    public function get_book_sentence_detail($sentenceId, $userId = 0)
    {

        $sql = "SELECT  id,
                        book_name,
                        content,
                        bg_img,
                        IF(FIND_IN_SET($userId,like_users),1,0) as is_like,
                        like_users,
                        publish_date
                  FROM book_sentence
                  WHERE id = $sentenceId";

        $sentenceInfo = DB::select($sql);
        if ($sentenceInfo) {
            $sentenceInfo            = $sentenceInfo[0];
            $time                    = strtotime($sentenceInfo->publish_date);
            $sentenceInfo->show_date = date('d/M', $time);
        }
        return $sentenceInfo;
    }

    /**
     * 更新书籍句子
     * @param $sentenceId integer 书籍句子ID
     * @param $sentenceInfo array 句子信息
     * */
    public function update_sentence($sentenceId, array $sentenceInfo)
    {
        return DB::table('book_sentence')->where('id', $sentenceId)->update($sentenceInfo);
    }


}


